package com.yyq.sqlSession;

import com.yyq.pojo.BoundSql;
import com.yyq.pojo.Configuration;
import com.yyq.pojo.MappedStatement;
import com.yyq.utils.GenericTokenParser;
import com.yyq.utils.ParameterMapping;
import com.yyq.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author yuanyueqiang
 * @Date 2021-11-27 23:06
 */
public class SimpleExecutor implements Executor {

    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement mappedStatement, Object... params)
            throws Exception {
        //1. 注册jdbc驱动
        Connection connection = configuration.getDataSource().getConnection();
        //2. 获取sql语句
        String sql = mappedStatement.getSql();
        //3. 转换sql语句, 要对#{}中的值进行解析存储
        BoundSql boundSql = getBoundSql(sql);
        //4. 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //5. 设置参数,执行sql
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassByType(parameterType);
        List<ParameterMapping> list = boundSql.getParameterMappingList();
        for (int i = 0; i < list.size() ; i++) {
            ParameterMapping parameterMapping = list.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        //6. 处理返回结果集
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassByType(resultType);
        ArrayList<Object> resultList = new ArrayList<>();
        while(resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段值
                Object object = resultSet.getObject(columnName);
                //使用反射或者内省, 根据数据库表或者实体的对应关系, 完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, object);
            }
            resultList.add(o);
        }
        return (List<T>) resultList;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //1. 注册jdbc驱动
        Connection connection = configuration.getDataSource().getConnection();
        //2. 获取sql语句
        String sql = mappedStatement.getSql();
        //3. 转换sql语句, 要对#{}中的值进行解析存储
        BoundSql boundSql = getBoundSql(sql);
        //4. 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //5. 设置参数,执行sql
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassByType(parameterType);
        List<ParameterMapping> list = boundSql.getParameterMappingList();
        for (int i = 0; i < list.size() ; i++) {
            ParameterMapping parameterMapping = list.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        int count = preparedStatement.executeUpdate();
        return count;
    }

    private Class<?> getClassByType(String parameterType) throws ClassNotFoundException {
        if(parameterType!=null){
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }

    /**
     * 解析sql
     *  1. 将sql中#{}用?代替
     *  2. 解析除#{中的值进行存储}
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        //解析出来的sql
        String parseSql = tokenParser.parse(sql);
        //#{}中的内容列表
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
        return boundSql;
    }
}
